/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.core;

import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cool.taomu.software.fig.mqtt.client.paho.MQTTSender;
import cool.taomu.software.fig.mqtt.client.paho.entity.SenderEntity;
import cool.taomu.software.fig.mqtt.utils.CommonUtils;

public class MqttCallSite {

	static final Logger LOG = LoggerFactory.getLogger(MqttCallSite.class);

	static final BlockingQueue<SenderEntity> QUEUE = new LinkedBlockingQueue<SenderEntity>();

	static {
		CommonUtils.exec(new Runnable() {
			@Override
			public void run() {
				try {
					SenderEntity entity = null;
					while ((entity = QUEUE.take()) != null) {
						MQTTSender send = new MQTTSender();
						send.publish(entity);
					}
					LOG.info("sendMessageTakeQueue 结束了");
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					LOG.error("中断错误", e);
				}
			}
		});
	}

	public static void clientCallSite(final String zlassName, final String methodName, final String topic,
			final MqttMessage message) {
		CommonUtils.exec(new MqttMessageProcessing(zlassName, message, topic, methodName, QUEUE));
	}

	public static CallSite bootstrap(final MethodHandles.Lookup caller, final String name, final MethodType type)
			throws NoSuchMethodException, IllegalAccessException {
		MethodHandles.Lookup lookup = MethodHandles.lookup();
		Class<?> thisClass = lookup.lookupClass();
		MethodHandle sayHello = lookup.findStatic(thisClass, "clientCallSite",
				MethodType.methodType(void.class, String.class, String.class, String.class, MqttMessage.class));
		return new ConstantCallSite(sayHello);
	}
}
